package com.freight.base.serviceimpl;


import com.alibaba.fastjson.JSONObject;
import com.freight.base.dao.PlatformRulesDao;
import com.freight.base.entity.PlatformRules;
import com.freight.base.service.PlatformRulesService;
import com.freight.base.vo.PlatformRulesVo;
import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
@Transactional
public class PlatformRulesServiceImpl implements PlatformRulesService {

    @Autowired
    private PlatformRulesDao platformRulesDao;

    @Autowired
    SecurityUtil securityUtil;

    @Value("${file-save-path}")
    private String fileSavePath;

    @Override
    public void savePlatformRules(String content) {
        PlatformRules platformRules;
        JSONObject json=JSONObject.parseObject(content);
        String fileName=Math.round((Math.random()+1) * 1000)+"";

        Long id=json.getLong("id");
        String title=json.getString("title");
        String rulesType=json.getString("rulesType");
        String rulesContent=json.getString("rulesContent");

        rulesContent="<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body>"+rulesContent+"</body></html>";
        if(id!=null && id > 0){
            platformRules=platformRulesDao.getOne(id);
            if (platformRules!=null){
                fileName=platformRules.getRulesPath().substring(15,19);
            }
        }else {
            platformRules=new PlatformRules();
        }

        platformRules.setTitle(title);
        platformRules.setRulesType(rulesType);

        String newFileName= fileName+".html";
        File newFile = new File(fileSavePath + newFileName);

        platformRules.setRulesPath("/platformrules/"+newFileName);

        try {
            //1、创建OutputStreamWriter对象，构造方法中传递字节输出流和指定编码表 utf-8 gbk
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileSavePath + newFileName), "utf-8");
            //2、使用write方法把字符转换位字节存贮到缓冲区中
            osw.write(rulesContent);
            //3、使用flush方法把字节刷新到文件中去
            osw.flush();
            //4、释放资源
            osw.close();

//            PrintStream ps = new PrintStream(new FileOutputStream(newFile));
//            ps.println(rulesContent);// 往文件里写入字符串
        } catch (IOException e) {
            //"IO异常！"
        }
        platformRulesDao.save(platformRules);
    }

    @Override
    public void deletePlatformRules(Long id) {
        if (id!=null && id>0){
            PlatformRules platformRules=new PlatformRules();
            platformRules.setId(id);
            platformRulesDao.delete(platformRules);
        }else {
            throw new FreightException("参数错误");
        }

    }

    @Override
    public PlatformRulesVo getPlatformRulesId(Long id) {
        PlatformRulesVo platformRulesVo=new PlatformRulesVo();
        if (id!=null && id>0){
            PlatformRules platformRules=platformRulesDao.getOne(id);
            if (platformRules!=null&&platformRules.getId()!=null) {
                String newFileName = platformRules.getRulesPath().substring(15, 24);
                File newFile = new File(fileSavePath + newFileName);
                StringBuffer sbf = new StringBuffer();

                FileInputStream fis= null;
                try {
                    fis = new FileInputStream(newFile);
                    InputStreamReader isr=new InputStreamReader(fis,"UTF-8");
                    BufferedReader br = new BufferedReader(isr);
                    String tempStr;
                    while ((tempStr = br.readLine()) != null) {
                        sbf.append(tempStr);
                    }
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


//                BufferedReader reader = null;
//                try {
//                    reader = new BufferedReader(new FileReader(newFile));
//                    String tempStr;
//                    while ((tempStr = reader.readLine()) != null) {
//                        sbf.append(tempStr);
//                    }
//                    reader.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

                platformRulesVo.setContent(sbf.toString());
                platformRulesVo.setId(platformRules.getId());
                platformRulesVo.setRulesType(platformRules.getRulesType());
                platformRulesVo.setRulesPath(platformRules.getRulesPath());
                platformRulesVo.setTitle(platformRules.getTitle());


            }
        }else {
            throw new FreightException("参数错误");
        }
        return platformRulesVo;
    }

    @Override
    public Page<PlatformRules> getPlatformRulesPage(Pageable pageable) {
        User u = securityUtil.getCurrUser();

        Page<PlatformRules> res = platformRulesDao.findAll(new Specification<PlatformRules>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<PlatformRules> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                cq.orderBy(cb.desc(root.get("createTime")));
                return null;
            }
        }, pageable);

        return res;

    }

    @Override
    public List<PlatformRules> getPlatformRulesList() {
        User u = securityUtil.getCurrUser();

        Specification specification = new Specification<PlatformRules>() {
            @Override
            public Predicate toPredicate(Root<PlatformRules> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<String> rulesType = root.get("rulesType");

                List<Predicate> list = new ArrayList<Predicate>();
                List<Predicate> predicateList = new ArrayList<>();

                if (u.getUserType() == CommonConstant.USER_TYPE_DRIVER) {
                    predicateList.add(cb.equal(rulesType, "1"));
                    predicateList.add(cb.equal(rulesType, "4"));
                }

                if (u.getUserType() == CommonConstant.USER_TYPE_COMPANY) {
                    predicateList.add(cb.equal(rulesType, "2"));
                    predicateList.add(cb.equal(rulesType, "4"));
                }

                list.add(cb.or(predicateList.toArray(new Predicate[predicateList.size()])));

                Predicate[] arr = new Predicate[list.size()];

                return query.where(list.toArray(arr)).getRestriction();
            }

        };

        if (u.getUserType() == CommonConstant.USER_TYPE_DRIVER || u.getUserType() == CommonConstant.USER_TYPE_COMPANY){
            return platformRulesDao.findAll(specification);
        } else {
            return platformRulesDao.findAll();
        }

    }

}
